import { EventEmitter } from "events";
import path from "node:path";
import { app, type BrowserWindow } from "electron";
import * as child_process from "node:child_process";
import { IS_DEV } from "@electron/main/util/env";
import type { UnzipCompleteArgs, UnzipErrorArgs } from "@common/archives-file-types";

const _7zBin = IS_DEV
  ? path.resolve(process.cwd(), `thirdparty/7z/${process.platform}/${process.arch}/7za`)
  : path.resolve(path.dirname(app.getPath("exe")), `thirdparty/7z/${process.platform}/${process.arch}/7za`);

/**
 * 解压任务
 */
export class UnzipTask extends EventEmitter {
  private _proc?: child_process.ChildProcessWithoutNullStreams;

  constructor(
    readonly id: string,
    readonly archvieFile: string,
    readonly outputDir: string,
    readonly wind: BrowserWindow | undefined,
  ) {
    super();
  }

  start() {
    const proc = child_process.spawn(_7zBin, ["x", this.archvieFile, "-o" + this.outputDir, "-y"], { windowsHide: true });
    proc.on("error", err => {
      this.emit("error", err);
      this.wind?.webContents?.send(`unzip:error:${this.id}`, { message: err.message } as UnzipErrorArgs);
      console.error(err);
    });
    proc.on("exit", code => {
      if (code === 0) {
        this.emit("complete");
        this.wind?.webContents?.send(`unzip:complete:${this.id}`, { sourceFile: this.archvieFile, fileDir: this.outputDir } as UnzipCompleteArgs);
      }
    });
    this._proc = proc;
    if (IS_DEV) {
      console.log("start unzip task =>", this.id, this.archvieFile, this.outputDir);
    }
    if (IS_DEV) {
      proc.stdout.on("data", data => {
        console.log(data.toString()?.trimEnd());
      });
    }
  }

  cancel() {
    this._proc?.kill();
    this._proc = undefined;
  }
}
